package mysqlLib

import (
	"database/sql"
	"errors"
	"log"
	"strings"
)
import _ "github.com/go-sql-driver/mysql"

const (
	mysqlUser = "root"
	mysqlPassword = "DZL123456"
	mysqlHost = "localhost"
	mysqlPort = "3306"
	db = "HHLAB_management"
)

func NewConnection() *sql.DB{
	db, err := sql.Open("mysql", mysqlUser+":"+mysqlPassword+"@tcp"+"("+mysqlHost+":"+mysqlPort+")/"+db)
	if err != nil {
		log.Printf("mysql connection error : %s", err)
		return nil
	}
	return db
}

func Query(sqlStr string, args... interface{}) ([]interface{}, error) {
	if len(args) != strings.Count(sqlStr, "?") {
		err := errors.New("sql params not match input args")
		log.Print(err)
		return nil, err
	}
	// select
	db := NewConnection()
	defer db.Close()
	// query : select gatewayid from tablename where id = 1
	rows, err := db.Query(sqlStr, args...)
	if err != nil {
		log.Printf("mysql query error :%s", err)
		return nil, err
	}
	var result interface{}
	var results []interface{}
	for rows.Next() {
		err := rows.Scan(&result)
		log.Printf("scan result is :%s", result)
		if err != nil {
			log.Printf("get data error: %s", err)
			return nil, err
		}
		results = append(results, result)
	}
	return results, nil
}

func Exec(sqlStr string, args ...interface{})  error {
	// insert or update
	//if len(args) == 0 {
	//	err := errors.New("args count zero")
	//	log.Print(err)
	//	return err
	//}
	if len(args) != strings.Count(sqlStr, "?") {
		err := errors.New("sql params not match input args")
		log.Print(err)
		return err
	}
	db := NewConnection()
	defer db.Close()
	_, err := db.Exec(sqlStr, args...)
	if err != nil {
		log.Printf("mysql exec sql error :%s", err)
	}

	return err
}
